﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ImageCompression
{
    /// <summary>
    /// 扩展方法
    /// Bao
    /// 联系：gsbhz@qq.com
    /// </summary>
    public static class ExtendMethod
    {
        #region 把文件附加到表格里
        /// <summary>
        /// 把文件附加到表格里
        /// </summary>
        /// <param name="gv"></param>
        /// <param name="list"></param>
        public static void Append(this DataGridView gv, Label lblProgress, List<ImgInfoEntity> list)
        {
            DataGridViewRow row = null;
            foreach (ImgInfoEntity e in list)
            {
                gv.Rows.Add();

                row = gv.Rows[gv.Rows.Count - 1];

                row.Cells["FileName"].Value = e.FileName;
                row.Cells["Bytes"].Value = e.Bytes;
                row.Cells["Size"].Value = e.Size;
                row.Cells["FullPath"].Value = e.FullPath;
            }
            lblProgress.Text = "0/" + gv.Rows.Count;
            if (row != null)
                row.Dispose();
        }
        #endregion

        #region 把表格转换成 List<ImgInfoEntity>
        public static List<ImgInfoEntity> ToList(this DataGridView gv)
        {
            List<ImgInfoEntity> list = new List<ImgInfoEntity>();
            foreach (DataGridViewRow row in gv.Rows)
            {
                list.Add(new ImgInfoEntity()
                {
                    FileName = row.Cells["FileName"].Value.ToString(),
                    Bytes = row.Cells["Bytes"].Value.ToString(),
                    //NewBytes = row.Cells["NewBytes"].Value.ToString(),
                    Size = row.Cells["Size"].Value.ToString(),
                    //NewSize = row.Cells["NewSize"].Value.ToString(),
                    FullPath = row.Cells["FullPath"].Value.ToString()
                });
            }
            return list;
        }
        #endregion

        #region 把 string 转换成 int
        /// <summary>
        /// 把 string 转换成 int
        /// </summary>
        /// <param name="s"></param>
        /// <returns>如果不能正确转换，则返回 int.MinValue</returns>
        public static int ToInt(this string s)
        {
            if (string.IsNullOrEmpty(s)) return int.MinValue;

            int result;
            if (!int.TryParse(s, out result)) return int.MinValue;

            return result;
        }
        #endregion
    }
}
